const express = require('express');
const OSS = require('ali-oss');
const path = require('path');
const { pool, initializeDatabase } = require('./db');
require('dotenv').config();

const app = express();
app.use(express.json());

// 数据库存储数据的API
// 服务器启动时初始化数据库
(async () => {
  try {
    await initializeDatabase();
  } catch (error) {
    console.error('初始化数据库失败:', error);
    process.exit(1);
  }
})();

// OSS客户端配置
const client = new OSS({
  region: process.env.OSS_REGION,
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  bucket: process.env.OSS_BUCKET,
});

// 提供静态资源web服务
app.use(express.static(path.join(__dirname, 'public')));

// 生成上传用的预签名URL
app.get('/api/upload-url', async (req, res) => {
  try {
    const { filename, contentType } = req.query;
    if (!filename || !contentType) {
      return res.status(400).json({ error: '文件名和内容类型是必需的' });
    }

    // 生成唯一文件名
    const key = `uploads/${Date.now()}-${filename}`;
    
    // 生成预签名URL，有效期1小时
    const url = client.signatureUrl(key, {
      method: 'PUT',
      expires: 3600,
      'Content-Type': contentType
    });

    res.json({ 
      uploadUrl: url,
      fileKey: key,
      expiresIn: 3600
    });
  } catch (error) {
    console.error('生成预签名URL失败:', error);
    res.status(500).json({ error: '生成预签名URL失败' });
  }
});

app.post('/api/reviews', async (req, res) => {
  const { userId, userName, restaurantName, restaurantLocation, dishName, rating, reviewText, imageKeys } = req.body;

  // 验证请求数据
  if (!userId || !userName || !restaurantName || !rating || !reviewText || !imageKeys) {
    return res.status(400).json({ error: '所有字段都是必需的' });
  }

  if (typeof userId !== 'number' || typeof rating !== 'number') {
    return res.status(400).json({ error: 'userId 和 rating 必须是数字' });
  }

  // 与数据库交互
  try {
    const [result] = await pool.query(
      `
        INSERT INTO reviews (
          userId, userName, restaurantName, restaurantLocation, dishName, rating, reviewText, imageKeys
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
      `,
      [userId, userName, restaurantName, restaurantLocation, dishName, rating, reviewText, imageKeys]
    );

    res.status(201).json({ message: 'Review saved successfully', id: result.insertId });
  } catch (error) {
    console.error('Error saving review:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});